package com.example.administrator.hqq.fragment.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SPUtils;
import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.FloatMenu;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.activity.complain.ChatComplainActivity;
import com.example.administrator.hqq.adapter.dialog.DIalogContactAdapter;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.base.MyFragemnt;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.DIalogContactBean;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.fragment.DIspatchTouchEvent;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import io.rong.push.RongPushClient;
import okhttp3.Call;


public class ContactFragment extends MyFragemnt {
    @BindView(R.id.recycler)
    RecyclerView recycler;
    Unbinder unbinder;
    @BindView(R.id.SmartRefreshLayout)
    com.scwang.smartrefresh.layout.SmartRefreshLayout SmartRefreshLayout;
    private String TAG = this.getClass().getSimpleName();
    private List<DIalogContactBean.DataBean> data;
    private DIalogContactAdapter dIalogContactAdapter;
    private Point point = new Point();
    private AlertDialog alertDialog;
    private List<String> strings;
    private List<String> deleteId;

    @Override
    public void onAttach(Context context) {

        ((MainActivity) getActivity()).setdIspatchTouchEvent(new DIspatchTouchEvent() {
            @Override
            public void onDispatchTouchEvent(MotionEvent ev) {
                if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                    point.x = (int) ev.getRawX();
                    point.y = (int) ev.getRawY();
                }
            }
        });
        super.onAttach(context);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_contact, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        initview();
        indata();
        EventBus.getDefault().register(this);
        return inflate;
    }

    private void indata() {
        OkHttpUtils.get().url(UrlFactory.getGetcontactlist())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                if (SmartRefreshLayout != null) {
                    SmartRefreshLayout.finishLoadMore();
                    SmartRefreshLayout.finishRefresh();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                DIalogContactBean dIalogContactBean = gson.fromJson(response, DIalogContactBean.class);
                if (SmartRefreshLayout != null) {
                    SmartRefreshLayout.finishLoadMore();
                    SmartRefreshLayout.finishRefresh();
                }
                if (dIalogContactBean.getCode() == 200) {
                    data.clear();
                    data.addAll(dIalogContactBean.getData());
                    for (int i = 0; i < data.size(); i++) {
                        int intValue = SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).getInt(data.get(i).getTopic_id() +
                                LoongsConfig.contact_is_showw, 1);
                        data.get(i).setIs_show(intValue == 0);
                    }
                    for (DIalogContactBean.DataBean datum : data) {
                        for (final DIalogContactBean.DataBean.ContactBean contactBean : datum.getContact()) {
                            String id1 = contactBean.getId();
                            deleteId.add(id1);
                        }
                    }
//                    RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
//                        @Override
//                        public void onSuccess(List<Conversation> conversations) {
//                            if (deleteId != null && deleteId.size() > 0 && conversations != null && conversations.size() > 0) {
//
//                                for (Conversation conversation : conversations) {
//                                    boolean isDelete = true;
//                                    for (String s : deleteId) {
//                                        if (s.equals(conversation.getTargetId())) {
//                                            isDelete = false;
//                                        }
//                                    }
//                                    if (isDelete)
//                                        MyApplication.removeRongyunConversation(conversation.getConversationType(), conversation.getTargetId());
//                                }
//                            }
//                        }
//                        @Override
//                        public void onError(RongIMClient.ErrorCode errorCode) {
//                        }
//                    });
                    dIalogContactAdapter.notifyDataSetChanged();
                }
                updateConversationList();
            }
        });
    }

    private void updateConversationList() {
        for (DIalogContactBean.DataBean datum : data) {
            for (DIalogContactBean.DataBean.ContactBean contactBean : datum.getContact()) {
                if (contactBean.getType() == 0) {
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(contactBean.getId(), contactBean.getTitle(), Uri.parse(contactBean.getUrl())));
                } else {
                    RongIM.getInstance().refreshGroupInfoCache(new Group(contactBean.getId(), contactBean.getDialog_title(), Uri.parse(contactBean.getUrl())));
                }
            }
        }
    }

    private void initview() {
        deleteId = new ArrayList();
        strings = new ArrayList<>();
        data = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recycler.setLayoutManager(linearLayoutManager);
        dIalogContactAdapter = new DIalogContactAdapter(data, getContext());
        recycler.setAdapter(dIalogContactAdapter);
        dIalogContactAdapter.setOnClickItem(new DIalogContactAdapter.OnClickItem() {
            @Override
            public void onClikeItem(int position) {
                data.get(position).setIs_show(!data.get(position).isIs_show());
                SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(data.get(position).getTopic_id() +
                        LoongsConfig.contact_is_showw, data.get(position).isIs_show() ? 0 : 1);
                dIalogContactAdapter.notifyDataSetChanged();
            }

            @Override
            public void onClickeChild(int position, int childpositing) {
                SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ConversationID, data.get(position).getContact().get(childpositing).getId());
                if (data.get(position).getContact().get(childpositing).getType() == 0) {
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.PRIVATE);
                    RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.PRIVATE, data.get(position).getContact().get(childpositing).getId(), "");

                } else {
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.GROUP);
                    RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.GROUP, data.get(position).getContact().get(childpositing).getId(), "");
                }
            }

            @Override
            public void onLongClickeChild(final int position, final int childpositing) {
                final FloatMenu floatMenu = new FloatMenu(getActivity());
                String s = "移除并退出该群";
                if (data.get(position).getContact().get(childpositing).getType() == 0)
                    s = "删除并拉黑联系人";
                floatMenu.items(450, s);
                floatMenu.setOnItemClickListener(new com.noober.menu.FloatMenu.OnItemClickListener() {
                    @Override
                    public void onClick(View v, int position1) {
                        if (data.get(position).getContact().get(childpositing).getType() == 0) {
                            showGontactDialog(data.get(position).getContact().get(childpositing).getId());
                        } else {
                            showGroupDialog(position, childpositing);
                        }
                    }
                });
                floatMenu.show(point);
            }
        });
        //设置刷新动画
        SmartRefreshLayout.setEnableAutoLoadMore(false);
        SmartRefreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        SmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                indata();
            }
        });
    }

    private void showGroupDialog(final int position1, final int childpositing) {
        alertDialog = AlertViewFactory.getInstance().showLeaveGroupReport(getContext(), new AlertViewFactory.DeleteFriendReportOnclicke() {
            @Override
            public void submit(int position) {
                deleteGroup(position1, childpositing);
                alertDialog.cancel();
            }

            @Override
            public void goComplain(int position) {
                deleteGroup(position1, childpositing);
                Log.e(TAG, "goComplain: " + LoongsConfig.ComplainType.GROUP.toString());
                ChatComplainActivity.start(getContext()
                        , RongPushClient.ConversationType.GROUP.toString()
                        , data.get(position).getContact().get(childpositing).getId()
                        , data.get(position).getContact().get(childpositing).getId()
                        , LoongsConfig.ComplainType.QUIT_GROUP.toString());
            }
        });

    }

    private void showGontactDialog(final String id) {
        strings.clear();
        String[] stringArray = getResources().getStringArray(R.array.delete_friend);
        for (String s : stringArray) {
            strings.add(s);
        }
        alertDialog = AlertViewFactory.getInstance().showDeleteFriendReport(getContext(), "评价该用户", "其他严重违法情形,请前往投诉", strings, new AlertViewFactory.DeleteFriendReportOnclicke() {
            @Override
            public void submit(int position) {
                reportFriend(position, id);
                alertDialog.cancel();
            }
            @Override
            public void goComplain(int position) {
                alertDialog.cancel();
                ChatComplainActivity.start(getActivity()
                        , RongPushClient.ConversationType.PRIVATE.toString(), id, id, LoongsConfig.ComplainType.PRIVATE.toString());
            }
        });
    }

    /**
     * 举报用户
     *
     * @param position
     * @param other_id
     */
    private void reportFriend(int position, final String other_id) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, other_id)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id, position + 601 + "")
                .addParams(LoongsConfig.type, "5")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "举报用户onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                indata();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        MyApplication.removeRongyunConversation(Conversation.ConversationType.PRIVATE, other_id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "举报用户onResponse: " + response);
            }
        });
    }

    /**
     * 删除群聊接口
     *
     * @param position
     * @param childpositing
     */
    private void deleteGroup(final int position, final int childpositing) {
        OkHttpUtils.get().url(UrlFactory.setActiveExit())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, data.get(position).getContact().get(childpositing).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "删除群聊接口onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "删除群聊接口onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        MyApplication.removeRongyunConversation(Conversation.ConversationType.GROUP, data.get(position).getContact().get(childpositing).getId());
                        data.get(position).getContact().remove(childpositing);
                        dIalogContactAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 单聊删除接口
     * @param position
     * @param childpositing
     */
    private void deleteContact(final int position, final int childpositing) {
        OkHttpUtils.get().url(UrlFactory.deleteContact())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.user_other_id, data.get(position).getContact().get(childpositing).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "删除单聊接口onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "删除单聊接口onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        data.get(position).getContact().remove(childpositing);
        dIalogContactAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(GroupEvent groupEvent) {
        switch (groupEvent.getType()) {
            case DELETE_GROUP:
                indata();
                break;
            case CREATE_GROUP:
                indata();
                break;
            case ALTER_GROUP:
                indata();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Complain complain) {
        if (complain != null) {
            switch (complain.getType()) {
                case JOIN_GROUP:
                    indata();
                case QUIT_GROUP:
                case DELETE_FRIEND:
                    delelteData(complain.getObjectId());
                    break;
                case KICK_MEMBER:
                    break;
                case NO_QUIT_GROUP:
                    break;
                case DIRECTCHAT:
                    indata();
                    break;
            }
        }
    }

    private void delelteData(String objectId) {
        for (DIalogContactBean.DataBean datum : data) {
            for (DIalogContactBean.DataBean.ContactBean contactBean : datum.getContact()) {
                if (contactBean.getId().equals(objectId)) {
                    datum.getContact().remove(contactBean);
                    dIalogContactAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

}
